package com.blog;

import okhttp3.*;

import java.io.IOException;
import java.util.*;

public class OkHttpUtils {
    static OkHttpClient client = initHttpClient();

    static OkHttpClient initHttpClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        // 支持的cookie使用
        builder.cookieJar(new CookieJar() {
            private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieStore.put(url.host(), cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        });
        return builder.build();
    }

    // 这个功能还是很完善，这里单纯是为了更快的测试
    public static void postReqWithoutRespData(String url, Map<String, String> requestMap) {
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : requestMap.keySet()) {
            builder.add(key, requestMap.get(key));
        }
        RequestBody formBody = builder.build();
        Request request = new Request.Builder().url(url).post(formBody).build();
        try {
            client.newCall(request).execute();
            System.out.println("登录成功。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //    Set-Cookie:login1=768012449%40qq.com; path=/; domain=.amazingcounters.com
//    Set-Cookie:pass1=hax1314; path=/; domain=.amazingcounters.com
    public static String getReqWithRespData(String url) {
        String string = "";
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            ResponseBody body = response.body();
            string = body.string();
            body.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return string;
    }
}
